package com.mars.tukuan.web.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.mars.base.common.base.BaseController;
import com.mars.base.common.base.BaseResult;
import com.mars.base.common.exception.AppException;
import com.mars.base.common.utils.Paginator;
import com.mars.component.mq.JmsQueueMessage;
import com.mars.component.redis.JedisClient;
import com.mars.tukuan.dto.CarCheckVo;
import com.mars.tukuan.dto.CarRepairVo;
import com.mars.tukuan.dto.CarStateVo;
import com.mars.tukuan.entity.CarCheck;
import com.mars.tukuan.rpc.api.CarCheckService;
import com.mars.tukuan.rpc.api.CarRepairService;
import com.mars.tukuan.rpc.api.CarService;
import com.mars.tukuan.rpc.api.CarStateService;
import com.mars.tukuan.rpc.api.CarUserService;
import com.mars.tukuan.utils.file.FileMeta;
import com.mars.tukuan.utils.file.FileUtil;
import com.mars.tukuan.utils.file.cloud.UploadCloudStroe;
import com.mars.tukuan.utils.file.cloud.UploadResult;

@RestController
@RequestMapping("/api/tukuan/mobile/car/check")
public class CarCheckController extends BaseController {

	@Autowired
	private CarCheckService service;

	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private JmsQueueMessage jmsQueueMessage;
	
	@Autowired
	private UploadCloudStroe uploadCloudStroe;
	
	@Autowired
	private CarService carService;
	
	@Autowired
	private CarCheckService carCheckService;
	
	@Autowired
	private CarStateService carStateService;
	
	@Autowired
	private CarUserService carUserService;
	
	@Autowired
	private CarRepairService repairService;

	@PostMapping(value = "/add")
	public Object add(CarCheck entity) {
		try {
			this.service.insertSelective(entity);
		} catch (Exception e) {
			return BaseResult.addFailed();
		}
		return BaseResult.addOk();
	}

	@GetMapping(value = "/delete/{ids}")
	public Object delete(@PathVariable String ids) {
		try {
			this.service.deleteByIds(ids);
		} catch (Exception e) {
			return BaseResult.deleteFailed();
		}
		return BaseResult.deleteOk();
	}

	@PostMapping(value = "/update")
	public Object update(CarCheck entity) {
		try {
			this.service.updateSelective(entity);
		} catch (Exception e) {
			return BaseResult.updateFailed();
		}
		return BaseResult.updateOk();
	}

	@GetMapping(value = "/get/{id}")
	public CarCheck get(@PathVariable Long id) {
		return this.service.selectById(id);
	}

	@GetMapping(value = "/list")
	public Object list(CarCheckVo entity) {
		try {
			return  this.service.list(new Paginator(request), entity) ;
		} catch (AppException e) {
			return BaseResult.loadFailed();
		}
	}

	@PostMapping(value = "/insertHandler")
	public Object insertHandler(@RequestBody CarCheckVo vo) {
		try {
			// 发送异步消息
			//this.jmsQueueMessage.send("car.check", vo);
			
			int carCheckId = this.service.insertHandler(vo) ;
			
			if(vo.isWx()) {//无伤
				CarStateVo entity = new CarStateVo() ;
				entity.setCarCheckId((long)carCheckId);
				entity.setIsHarm(2);
				entity.setCarId(vo.getCarId());
				entity.setBeforeUserId(vo.getCarUserId());
				entity.setBeforeTime(new Date());
				this.carStateService.insertSelective(entity) ;
			} else {//新伤
				List<CarStateVo> harms = vo.getHarms() ;
				if(null != harms) {
					for (CarStateVo carStateVo : harms) {
					
						carStateVo.setCarCheckId((long)carCheckId);
						carStateVo.setIsHarm(1);
						carStateVo.setFollow(1);
						this.carStateService.insertSelective(carStateVo) ;
					}
					//删除Redis缓存中的数据
					String key = "car:before_upload:" + vo.getCarUserId();
					this.jedisClient.del(key) ;
				}
			}
			
			//更新车况检查时间
			this.carService.updateCheckTime(vo.getCarId());
			//更新用户的车况见时间
			this.carUserService.updateCheckTime(vo.getCarUserId());
			
			//修改车辆保养信息的当前里程数
			CarRepairVo repair = new CarRepairVo() ;
			repair.setId(vo.getCarId());
			repair.setCarCurrMileage(Double.parseDouble(vo.getMileage()));
			this.repairService.updateCurrent(repair);
			
		} catch (Exception e) {
			return BaseResult.addFailed();
		}
		return BaseResult.addOk();
	}

	/**
	 * 上传新伤图片
	 * 
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/upload_xs")
	public Object upload_xs(CarStateVo vo, HttpServletRequest request) {
		try {

			List<FileMeta> upload = FileUtil.upload(request);
			if (!upload.isEmpty()) {
				FileMeta fileMeta = upload.get(0);
				
				UploadResult result = this.uploadCloudStroe.uploadFile(new File(fileMeta.getDestFilePath())) ;
				if(result.getStatus()) {
					vo.setBeforeImageUrl(result.getFileUrl());
					
					String key = "car:before_upload:" + vo.getBeforeUserId();

					this.jedisClient.setHash(key, vo.gethField(), JSON.toJSONString(vo));
				}
			}

		} catch (Exception e) {
			return BaseResult.failure();
		}
		return BaseResult.ok();
	}

	/**
	 * 从Redis中获取用户上传新伤信息
	 * 
	 * @param vo
	 * @return
	 */
	@GetMapping(value = "/getUploadXsInfo/{userId}")
	public Object getUploadXsInfo(@PathVariable Long userId) {
		String key = "car:before_upload:" + userId;
		Map<String, String> hashAll = this.jedisClient.getHashAll(key);
		return hashAll;
	}
	
	@GetMapping(value = "/cleanUploadXsInfo/{userId}")
	public void cleanUploadXsInfo(@PathVariable Long userId) {
		String key = "car:before_upload:" + userId;
		this.jedisClient.del(key);
	}

	@GetMapping(value = "/delUploadXsInfo/{userId}/{hField}")
	public void delUploadXsInfo(@PathVariable Long userId, @PathVariable String hField) {
		String key = "car:before_upload:" + userId;
		this.jedisClient.delHash(key, hField) ;
	}
	
	/**
	 * 当用户点击新伤按钮时，缓存用户选择过的数据
	 * @param vo
	 */
	@PostMapping(value = "/cacheCarCheckChoose")
	public void cacheCarCheckChoose(CarCheckVo vo) {
		String key = "car:check:choose:" + vo.getCarUserId();
		this.jedisClient.set(key, JSON.toJSONString(vo));
	}
	/**
	 * 获取用户缓存的车辆检查表数据
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/getCarCheckChoose/{userId}")
	public CarCheckVo getCarCheckChoose(@PathVariable Long userId) {
		String key = "car:check:choose:" + userId;
		String string = this.jedisClient.get(key) ;
		return JSON.parseObject(string, CarCheckVo.class);
	}
	/**
	 * 删除缓存
	 * @param userId
	 */
	@GetMapping(value = "/cleanCarCheckChoose/{userId}")
	public Object cleanCarCheckChoose(@PathVariable Long userId) {
		String key = "car:check:choose:" + userId;
		this.jedisClient.del(key);
		return BaseResult.ok();
	}
	

}
